namespace org.lionsoul.ip2region
{

	/// <summary>
	/// item index class
	/// 
	/// @author chenxin<chenxin619315@gmail.com>
	/// </summary>
	public class IndexBlock
	{
		private static int LENGTH = 12;

		/// <summary>
		/// start ip address 
		/// </summary>
		private long startIp;

		/// <summary>
		/// end ip address 
		/// </summary>
		private long endIp;

		/// <summary>
		/// data ptr and data length 
		/// </summary>
		private int dataPtr;

		/// <summary>
		/// data length 
		/// </summary>
		private int dataLen;

		public IndexBlock(long startIp, long endIp, int dataPtr, int dataLen)
		{
			this.startIp = startIp;
			this.endIp = endIp;
			this.dataPtr = dataPtr;
			this.dataLen = dataLen;
		}

		public virtual long StartIp
		{
			get
			{
				return startIp;
			}
		}

		public virtual IndexBlock setStartIp(long startIp)
		{
			this.startIp = startIp;
			return this;
		}

		public virtual long EndIp
		{
			get
			{
				return endIp;
			}
		}

		public virtual IndexBlock setEndIp(long endIp)
		{
			this.endIp = endIp;
			return this;
		}

		public virtual int DataPtr
		{
			get
			{
				return dataPtr;
			}
		}

		public virtual IndexBlock setDataPtr(int dataPtr)
		{
			this.dataPtr = dataPtr;
			return this;
		}

		public virtual int DataLen
		{
			get
			{
				return dataLen;
			}
		}

		public virtual IndexBlock setDataLen(int dataLen)
		{
			this.dataLen = dataLen;
			return this;
		}

		public static int IndexBlockLength
		{
			get
			{
				return LENGTH;
			}
		}

		/// <summary>
		/// get the bytes for storage
		/// </summary>
		/// <returns>    byte[] </returns>
		public virtual byte[] Bytes
		{
			get
			{
				/*
				 * +------------+-----------+-----------+
				 * | 4bytes        | 4bytes    | 4bytes    |
				 * +------------+-----------+-----------+
				 *  start ip      end ip      data ptr + len 
				*/
				byte[] b = new byte[12];
    
				Util.writeIntLong(b, 0, startIp); //start ip
				Util.writeIntLong(b, 4, endIp); //end ip
    
				//write the data ptr and the length
				long mix = dataPtr | ((dataLen << 24) & 0xFF000000L);
				Util.writeIntLong(b, 8, mix);
    
				return b;
			}
		}
	}
}